package atri.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class ImageController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @PostMapping
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件不能为空");
        }

        try {
            // 获取当前路径
            String workDir = System.getProperty("user.dir");


            File uploadDirPath = new File(workDir, uploadDir);
            if (!uploadDirPath.exists()) {
                uploadDirPath.mkdirs();
            }

            // 获取文件名并生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = StringUtils.getFilenameExtension(originalFilename);
            String newFilename = UUID.randomUUID().toString() + "." + fileExtension;

            // 创建目标文件路径
            File dest = new File(uploadDirPath, newFilename);
            file.transferTo(dest);

            // 返回文件的完整 URL
            String fileUrl = "/uploaded-files/" + newFilename;
            System.out.println(fileUrl);

            String hostUrl = "http://localhost:8080";  // 服务器网址
            String fullFileUrl = hostUrl + fileUrl;

            return ResponseEntity.ok().body(fullFileUrl);
        } catch (IOException e) {
            return ResponseEntity.status(500).body("文件上传失败，请稍后重试");
        }
    }
}
